#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include <QTime>
#include <QMutex>
#include <QStackedWidget>
#include "v4l2.h"
#include "yolo11.h"
#include "VideoDecoderThread.h"
#include <QPainter>
#include <QTouchEvent>
#include <QStatusBar>
#include <QLabel>

extern "C" {
    #include <libavcodec/avcodec.h>
    #include <libavformat/avformat.h>
    #include <libswscale/swscale.h>
}

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
namespace Ui { class ImageViewer; }
namespace Ui { class VideoPlayer; }


QT_END_NAMESPACE

class ImageViewer; // 照片
class VideoPlayer; // 视频

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

protected:
    bool event(QEvent *event) override;
 
private slots:
    void captureAndDisplayFrame();
    void snapshot();
    void startRecording();
    void stopRecording();
    void startStreaming();
    void stopStreaming();
    void startYolo();
    void stopYolo();

    void selectImage();  //选择本地图片
    void showPreviousImage(); //上一张图片
    void showNextImage(); //下一张图片
    void returnToCamera();   //返回到摄像头捕获

    void selectVideo();  //选择本地视频
    void playVideo();    //播放
    void togglePause();   //暂停
    void stopVideo();    //停止
    void showPreviousVideo(); //前一视频
    void showNextVideo();  //下一视频
    void returnToMain(); //返回到摄像头捕获

    void displayFrame(const QImage &image);
    void handleDecoderError(const QString &error);

signals:
    void recordingStopped(); // 信号：录制停止后触发

private:
    void updateButtonStates();
    void processYoloInference(uint8_t* frame_data, QImage& image); // YOLO 推理和绘制
    void handleTouchEvent(QTouchEvent *event); //处理触摸事件
    bool uploadToOss(const QString& localFile, const QString& objectKey); //OSS
    //图片
    void loadImageList();
    void displayImage(int index);
    //视频
    void loadVideoList();
    void displayVideo(int index);

    Ui::MainWindow *ui;
    Ui::ImageViewer *imageUi;
    Ui::VideoPlayer *videoUi;
    QStackedWidget *stackedWidget;
    QTimer *timer;
    QMutex mutex;
    V4L2Context v4l2_ctx;

    bool isRecording = false;
    bool isStreaming = false;
    bool isYoloRunning = false;
    bool isCameraActive = true; // 跟踪是否显示摄像头画面
    int frameCount = 0;

    // YOLO 相关
    rknn_app_context_t rknn_app_ctx; // YOLOv11 上下文
    bool yolo_initialized = false;

    //视频文件路径
    QString video_filename;

    // 图片查看相关
    QStringList imageList;
    int currentImageIndex = -1;  
    QLabel *prevImageLabel;
    QLabel *currentImageLabel;
    QLabel *nextImageLabel;

    // 视频播放相关
    QString videoFilePath;
    bool isVideoPlaying = false;
    bool isVideoPaused = false;
    QLabel *videoLabel;
    QStringList videoList;
    int currentVideoIndex = -1;

    VideoDecoderThread *decoderThread;
};
#endif // MAINWINDOW_H